<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                     |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 卖车用户
 */
namespace AuctionBack\Controller;

use AuctionCore\Account\Back\Employee;
use AuctionCore\AntNest\Sms;
use AuctionCore\CarOwner\Owner;
use AuctionCore\CarOwner\OwnerList as OwnerList;
use AuctionCore\CarOwner\OwnerUserList as OwnerUserList;
use AuctionCore\System\AuctionException;
use AuctionCore\System\SystemLog;
use AuctionCore\Common\Page;


class CarOwnerController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    public function index()
    {
        //获取父级渠道来源
        $pfrom = M("come_from")->where("pid=-2 AND is_delete=0")->select();
        $this->assign('pfrom', $pfrom);

        $comefrom_list = $this->get_comefrom_list();
        //城市对应的4s店
        $bc_city = $this->bc_city;
        $city_fours_list = array();
        foreach($bc_city as $kb=>$vb) {
            $city_fours = M("come_from")->alias('a')->field('a.from_id,a.from_name')
                ->join(C('DB_PREFIX') . 'fours as f ON a.from_id = f.channel_id')
                ->where(array('f.city'=>$kb))
                ->order('sort ASC,pid DESC')
                ->select();
            $city_fours_list[$kb] = $city_fours;
        }
        $this->assign('comefrom_list',$comefrom_list);
        $this->assign('city_fours_list',$city_fours_list);
        $this->display();
    }

    //车主列表
    public function ownerList()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = I("get.status/d");
        $params['brand_id'] = I('get.brand_id/d');
        $params['series_id'] = I('get.series_id/d');
        $params['location_area'] = I('get.location_area','');
        // $params['car_model'] = urldecode(I('get.car_model/s'));
        $params['start_time'] = I("get.start_time");
        $params['end_time'] = I("get.end_time");
        if ($params['status'] == '8') {
            $params['reserve_start_time'] = I('get.reserve_start_time','');
            $params['reserve_end_time'] = I('get.reserve_end_time','');
        }elseif($params['status'] == '2') {
            $params['trace_start_time'] = I('get.trace_start_time/s','');
            $params['trace_end_time'] = I('get.trace_end_time/s','');
        }
        $params['owner_id'] = I("get.owner_id");
        // $params['seller_name'] = I("get.seller_name");
        $params['phone'] = I("get.phone");
        $params['trace_type'] = I('get.trace_type');
        $params['comefrom'] = I('get.comefrom', -2);
        $params['location_area'] = I('get.location_area');
        $params['emp_id'] = $this->user_info['emp_id'];
        $params['from'] = I('get.from','');
        //检查权限
        $rules = "FenPei";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        $params['auth'] = $auth;
        //获取客服
        if ($auth) {
            //$kefu_list = Employee::get_emp_by_group_or_store(389);
            $kefu_list = Employee::get_branch_emp(C('SERVER.0'));
            $this->assign('kfs', $kefu_list);
        }
        //获取list
        $ol = new OwnerList();
        $result = $ol->getList($page, $size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        //分页
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
        $show = $Page->show();// 分页显示输出

        $this->assign('page', $show);// 赋值分页输出
        $this->assign('list', $list);
        $this->assign("business_status", C("BUSINESS_STATUS"));
        $this->assign('channel_type', C("CHANNEL_TYPE"));
        $this->assign("params", $params);
        $this->assign('p', $page);
        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }

    //检查预约状态
    public function check_reserve_status()
    {
        $owner_id = I("post.id/d", 0);
        if ($owner_id < 1) {
            $this->helpJsonResult(400, "车主ID 不正确!");
        }
        $ow = new Owner($owner_id);
        $owner = $ow->detail();

        //查看预约状态
        if ((int)$owner['service_id'] > 0 && $this->user_info['emp_id'] != $owner['service_id']) {
            $this->helpJsonResult(400, "已经被预约");
        }

        if ($owner['trace_type'] == 3) {//滞留的
            if ($owner['delay_status'] == 3 || $owner['delay_status'] == 4 || $owner['delay_status'] == 6) {
                $this->helpJsonResult(400, '等待调度处理完成');
            }
        }
        $this->helpJsonResult(200, 'success');
    }

    //预约
    public function ownerInfo()
    {
        $owner_id = I("get.id");
        $o = new Owner($owner_id);
        $owner = $o->detail();

        if($owner['business_status']>2){
            $this->error("非法操作");
        }

        //查看预约状态
        if ((int)$owner['service_id'] > 0 && $this->user_info['emp_id'] != $owner['service_id']) {
            $this->error("已经被预约");
        }
        //门店
        $store = new \AuctionCore\Other\Store();

        //驳回、改约、滞留查看预约地址
        if($owner['trace_type'] == 1 || $owner['trace_type'] == 2 || $owner['trace_type'] == 3){
            if($owner['service_method'] == 3){  //到店
                $map = array();
                $map['store_id'] = array('eq',$owner['sign_reserve_store']);
                $store_detail = $store->detail($map);
                $owner['reserve_addr'] = $store_detail['store_name'];

            }elseif($owner['service_method'] == 2){  //上门
                $addr = new \AuctionCore\Other\Address();
                $province = $addr->get_name_by_code($owner['reserve_province']);
                $city = $addr->get_name_by_code($owner['reserve_city']);
                $area = $addr->get_name_by_code($owner['reserve_area']);
                $owner['reserve_addr'] = $province . " " . $city . " " . $area . " " . $owner['reserve_address'];
            }else{
                $owner['reserve_addr'] = '未知';
            }
        }
        if ($owner['trace_type'] == 3) {
            //检测滞留状态
            if ($owner['delay_status'] == 1) {
                $rs = $o->update(array('delay_status' => 2));
                if (!$rs) {
                    echo "请重试!";
                    exit;
                }
            }

            if ($owner['delay_status'] == 3 || $owner['delay_status'] == 4 || $owner['delay_status'] == 6) {
                exit;
            }
        }

        //如果还未预约
        if ($owner['service_id'] != $this->user_info['emp_id']) {
            $data['service_id'] = $this->user_info['emp_id'];
            $data['business_status'] = 2;//状态改为跟踪中
            $result = $o->update($data);
            if (!$result) {
                //$this->helpJsRedirect("预约失败");
                echo "预约失败";
                exit;
            }
            /**
             * 记录预约日志
             */
            $reserve_info['owner_id'] = $owner_id;
            $reserve_info['emp_id'] = $this->emp_id;
            $reserve_info['type'] = 1; //员工预约记录:跟踪中
            Owner::save_reserve_log($reserve_info);
        }
        //获取跟踪日志
        $trace_log = $o->get_reserve_log();
        //1、员工预约 2、预约跟踪 3、跟踪失败 4跟踪成功 5、分配成功 501、检测成功 502、检测失败 5021、检测改约 5022、检测驳回 5023、检测流失 5024、检测退单 6、分配改约7、分配滞留
        $log_type = $log_type = C('RESERVE_TRACE_LOG_TYPE');

        //门店
        $map = array();
        $map['status'] = array('eq',0);
        $stores = $store->get_stores($map);

        $this->assign('stores', $stores);
        $this->assign('logs', $trace_log);
        $this->assign('log_type', $log_type);
        $this->assign('owner', $owner);
        $this->assign('channel_type', C("COME_FROM"));
        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }

    //新增用户信息
    public function add()
    {
        //获取渠道来源列表
        $from = M("come_from a")->join('INNER JOIN (SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->field("a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort")
            ->where("a.pid!=-2 AND a.is_delete=0 AND a.from_id!=-1")
            ->order("psort ASC,from_id ASC,pid DESC")
            ->select();
        $this->assign('from', $from);

        //门店
        $store = new \AuctionCore\Other\Store();
        $map = array();
        $map['status'] = array('eq',0);
        $stores = $store->get_stores($map);

        $this->assign('stores', $stores);


        //获取父级渠道来源
        $pfrom = M("come_from")->where("pid=-2 AND is_delete=0")->select();
        $this->assign('pfrom', $pfrom);

        $comefrom_list = $this->get_comefrom_list();
        //城市对应的4s店
        $bc_city = $this->bc_city;
        $city_fours_list = array();
        foreach($bc_city as $kb=>$vb) {
            $city_fours = M("come_from")->alias('a')->field('a.from_id,a.from_name')
                ->join(C('DB_PREFIX') . 'fours as f ON a.from_id = f.channel_id')
                ->where(array('f.city'=>$kb))
                ->order('sort ASC,pid DESC')
                ->select();
            $city_fours_list[$kb] = $city_fours;
        }
        $this->assign('comefrom_list',$comefrom_list);
        $this->assign('city_fours_list',$city_fours_list);
        
        $this->display();
    }

    //新增卖车用户
    public function addCarOwner()
    {
        $data = array();
        $data['seller_name'] = I("post.seller_name");
        $data['phone'] = I('post.phone');

        if(!validatePhone($data['phone'])){
            $this->helpJsonResult(400, "电话格式不正确");
        }
        $data['comefrom'] = I("post.comefrom");
        if ($data['comefrom'] === '') {
            $this->helpJsonResult(400, "请选择渠道来源");
        }
        $data['location_area'] = I('post.location_area');
        /* 新增用户信息车型 车型变为输入框,防止心(sang)血(xin)来(bing)潮(kuang)
         * 的产品再改回来特此注释
        $data['brand_id'] = I('post.brand_id');
        $data['series_id'] = I('post.series_id');
        $data['modal_id'] = I('post.modal_id');
         */
        $data['car_model'] = I('post.car_model');
        $data['first_reg_date'] = I('post.first_reg_date');
        $data['mileage'] = I('post.mileage');
        $data['reserve_remark'] = I("post.reserve_remark");
        $business_status = I('post.business_status/d', 0);
        if ($business_status < 1) {
            $this->helpJsonResult(400, "请选择预约状态");
        }
        $data['business_status'] = $business_status;

        $reserve_log = array();
        $action = '新增卖车用户: ';
        switch ($business_status) {
            case 4:
                $data = $this->reserveSuccess($data);
                $action .= "预约成功";
                break;
            case 2:
                $data = $this->continue_trace($data);
                $reserve_log['next_trace_time'] = $data['next_trace_time'];
                $action .= "继续跟踪";
                break;
            case 3:
                $data = $this->reserveFailed($data);
                $action .= "预约失败";
                break;
            default:
                $this->helpJsonResult(400, '状态错误');
                break;
        }
        $data['posttime'] = date("Y-m-d H:i:s", time());
        $data['service_id'] = $this->user_info['emp_id'];
        $owner_id = Owner::create($data);
        if ($owner_id < 1) {
            $this->helpJsonResult(500, "新增客户失败,请稍后再试");
        }
        //保存预约跟踪日志
        $reserve_log['owner_id'] = $owner_id;
        $reserve_log['emp_id'] = $this->emp_id;
        $reserve_log['type'] = $business_status;
        $reserve_log['remark'] = $data['reserve_remark'];
        Owner::save_reserve_log($reserve_log);
        //记录员工操作日志
        $log = array(
            'emp_id' => $this->user_info['emp_id'],
            'order_id' => 0,
            'car_id' => 0,
            'owner_id' => $owner_id,
            'action' => $action
        );
        SystemLog::add($log);
        $this->helpJsonResult(200, "成功");

    }

    //新增预约,更新状态
    public function upCarOwner()
    {
        $owner_id = I("post.owner_id/d", 0);
        if ($owner_id < 1) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        $ow = new Owner($owner_id);
        $owner_info = $ow->detail();

        if ($owner_info['business_status'] > 2) {
            $this->helpJsonResult(500, '处理过了');
        }

        if($owner_info['trace_type']==3){
            if (($owner_info['delay_status'] == 3 || $owner_info['delay_status'] == 4 ||  $owner_info['delay_status'] == 6)) {
                $this->helpJsonResult(500, '等待调度处理完成');
            }
        }

        $data = array();
        $data['owner_id'] = $owner_id;
        $data['seller_name'] = I("post.seller_name");
        $data['phone'] = $owner_info['phone'];
        $data['location_area'] = I("post.location_area");
        $data['car_model'] = I("post.car_model");
        $data['brand_id'] = I("post.brand_id");
        $data['series_id'] = I("post.series_id");
        $data['model_id'] = I("post.model_id");
        $data['first_reg_date'] = I("post.first_reg_date");
        $data['car_model'] = I('post.car_model');
        $data['mileage'] = I("post.mileage");
        $data['reserve_remark'] = I("post.reserve_remark", "");
        $data['business_status'] = I("post.business_status/d", 0);

        if (empty($data['business_status'])) {
            $this->helpJsonResult("请选择预约状态");
        }
        $reserve_log = array();
        $reserve_log['type'] = $data['business_status'];
        $action = "卖车用户: ";
        switch ($data['business_status']) {
            case 4: //预约成功
                $data = $this->reserveSuccess($data);
                $action .= "预约成功";
                break;
            case 2: //预约跟踪中
                $data = $this->continue_trace($data);
                $reserve_log['next_trace_time'] = I("post.next_trace_time");
                $action .= "继续跟踪";
                break;
            case 3: //预约失败
                $data = $this->reserveFailed($data);
                $action .= "预约失败";
                break;
            case -1://滞留同意等待
                $data['business_status'] = 2;
                $reserve_log['type'] = 201;
                if ($owner_info['delay_status'] == 2) {
                    $data['delay_status'] = 3;
                }
                $action .= "同意等待";
                break;
            default:
                $this->helpJsonResult(400, "请选择预约状态");
                break;
        }

        //如果延迟状态是调度处理完成 改为 正常单
        if ($owner_info['delay_status'] == 5) {
            $data['trace_type'] = 0;
            $data['delay_status'] = 0;
        }
        $ow = new Owner($data['owner_id']);
        $res = $ow->update($data);
        if (!$res) {
            $this->helpJsonResult(500, "失败,请稍后再试");
        }
        //保存预约跟踪日志
        $reserve_log['owner_id'] = $owner_id;
        $reserve_log['emp_id'] = $this->emp_id;

        $reserve_log['remark'] = $data['reserve_remark'];
        Owner::save_reserve_log($reserve_log);
        //记录员工操作日志
        $log = array(
            'emp_id' => $this->user_info['emp_id'],
            'order_id' => 0,
            'car_id' => 0,
            'owner_id' => $owner_id,
            'action' => "卖车用户-{$action}"
        );
        SystemLog::add($log);
        $this->helpJsonResult(200, "成功");
    }

    //预约成功
    private function reserveSuccess($data)
    {
        //检测车主姓名不能为空
        if (empty($data['seller_name'])) {
            $this->helpJsonResult(400, '车主姓名不能为空');
        }
        //检测车主电话
        if (empty($data['phone'])) {
            $this->helpJsonResult(400, '车主电话不能为空');
        }
        //车辆所在地
        if (empty($data['location_area'])) {
            $this->helpJsonResult(400, '车辆所在地不能为空');
        }
        //预约时间
        $data['reserve_time'] = I('post.reserve_time');
        if (empty($data['reserve_time'])) {
            $this->helpJsonResult(414, '请选择预约时间！');
        }

        $data['reserve_time'] = transform_date($data['reserve_time'], 2);
        $data['service_method'] = I("post.service_method/d", 0);

        if ($data['service_method'] < 1 || $data['service_method'] > 3) {
            $this->helpJsonResult(400, "请选择正确的服务方式");
        }

        if ($data['service_method'] == 2) {
            $data['reserve_province'] = I("post.reserve_province/d");
            $data['reserve_city'] = I("post.reserve_city/d");
            $data['reserve_area'] = I("post.reserve_area/d");
            $data['reserve_address'] = I("post.reserve_address");
            if (empty($data['reserve_province'])) {
                $this->helpJsonResult(413, '请选择地区');
            }
            if (empty($data['reserve_city'])) {
                $this->helpJsonResult(413, '请选择城市');
            }
            if (empty($data['reserve_area'])) {
                $this->helpJsonResult(413, '请选择区域');
            }
            if (empty($data['reserve_address'])) {
                $this->helpJsonResult(413, '请填写具体地址');
            }
        } else {
            $data['reserve_store'] = I('post.reserve_store/d');
            if (empty($data['reserve_store'])) {
                $this->helpJsonResult(413, '请选择门店');
            }
        }
        return $data;
    }

    //跟踪中
    private function continue_trace($data)
    {
        $data['next_trace_time'] = I("post.next_trace_time");

        if (empty($data['reserve_remark'])) {
            $this->helpJsonResult(400, '原因不能为空！');
        }
        if (empty($data['next_trace_time'])) {
            $this->helpJsonResult(400, '请选择下次跟踪时间！');
        }
        return $data;
    }

    //预约失败
    private function reserveFailed($data)
    {
        if (empty($data['reserve_remark'])) {
            $this->helpJsonResult(413, '原因不能为空！');
        }
        return $data;
    }

    //查看预约信息
    public function reserveInfo()
    {
        $owner_id = I("get.id");
        $o = new Owner($owner_id);
        $owner = $o->detail();
        $addr = new \AuctionCore\Other\Address();
        $province = $addr->get_name_by_code($owner['reserve_province']);
        $city = $addr->get_name_by_code($owner['reserve_city']);
        $area = $addr->get_name_by_code($owner['reserve_area']);
        $location_area = $addr->get_name_by_code($owner['location_area']);
        $owner['location_area'] = $location_area;
        $owner['address'] = $province . " " . $city . " " . $area . " " . $owner['reserve_address'];
        //门店信息
        $store = new \AuctionCore\Other\Store();
        $map = array();
        $map['store_id'] = array('eq',$owner['reserve_store']);
        $store_detail = $store->detail($map);
        $owner['reserve_store'] =  $store_detail['store_name'];
        $show_from = $this->get_from();  //获取渠道来源信息
        //获取跟踪日志
        $trace_log = $o->get_reserve_log();
        $log_type = C('RESERVE_TRACE_LOG_TYPE');
        $this->assign('logs', $trace_log);
        $this->assign('log_type', $log_type);
        $this->assign('owner', $owner);
        $this->assign('show_from', $show_from);
        $this->display();
    }

    //分配客服
    public function assignServer()
    {
        $owner_id = I('post.owner_id/d', '');
        if (empty($owner_id)) {
            $this->helpJsonResult(400, "车主信息错误!");
        }
        $service_id = I('post.service_id/d', '');
        if (empty($service_id)) {
            $this->helpJsonResult(400, "请选择客服");
        }
        $co = new Owner($owner_id);
        $car_owner = $co->detail();
        if (empty($car_owner)) {
            $this->helpJsonResult(404, "车主不存在");
        }
        $data['service_id'] = $service_id;
        $ok = $co->update($data);
        if (!$ok) {
            $this->helpJsonResult(500, " 分配失败,请稍后再试 ");
        }
        $this->helpJsonResult(200, "分配成功");
    }

    /**
     * 车主帐号列表
     * @author sam
     */
    public function user_list()
    {
        $p = I('get.p/d',1);
        $search_key = I('request.search_key', '');
        $limit = 10;
        $params = array(
            'search_key' => $search_key
        );
        $oul = new OwnerUserList();
        //dump($oul->condition);exit;
        $list = $oul->get($limit, $p, $params);
        $count = $oul->count($params);

        $page = new Page($count, $limit);
        $page_data = $page->page_data();

        //dump($list);exit;
        $this->assign('search_key', $search_key);
        $this->assign('list', $list);
        $this->assign('p', $p);
        $this->assign('page_data', $page_data);
        $this->display();
    }

    /**
     * 操作
     * @author sam
     */
    public function ci_op()
    {
        try {
            $username = $_POST['username'];
            $op_type = $_POST['op_type'];

            // dump($_POST);exit;
            if ($op_type == '3') {
                $this->ch_pasword_and_send($username);
            } else {
                $fu = new \AuctionCore\Account\FrontUser($username);
                if ($op_type === '0') {      //启用
                    $fu->enable();
                } else if ($op_type === '1') {  //禁用
                    $fu->disable();
                }
            }
            echo \AuctionCore\Common\Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo \AuctionCore\Common\Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    //更新帐号密码,并发送给车主
    private function ch_pasword_and_send($username)
    {
        $o = new \AuctionCore\CarOwner\Owner($username);
        $detail = $o->detail();
        //dump($detail);exit;
        $uid = $detail['uid'];

        $mobile = $detail['phone'];
        $new_password = rand(100000, 999999);
        if (!$uid) {
            //开通网站帐号
            $user_info = array();
            $user_info['user_name'] = $mobile;
            $user_info['passwd'] = $new_password;
            $user_info['nick_name'] = $detail['seller_name'];
            $user_info['pwd_mobile'] = $mobile;
            $user_info['sms_mobile'] = $mobile;
            $user_info['real_name'] = '';
            $uid = $o->enable_front_user($user_info);

            //发送密码
            $sms = new Sms();
            $tpl_data = ['username' => $user_info['user_name'], 'password' => $new_password];
            $ok = $sms->notify(1, $mobile, $tpl_data);
        } else {
            //更新帐号密码
            $fu = new \AuctionCore\Account\FrontUser($uid);
            $fu->reset_password();
            /*$user_info = $fu->user_info();
            $mobile = $user_info['pwd_mobile'];
            $ok = $fu->change_password($new_password);*/
        }
    }

    //获取渠道来源信息
    private function get_from()
    {
        $from = M("come_from a")->field("a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort")
            ->join('(SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->where("a.pid!=-2 AND a.is_delete=0")
            ->order("psort ASC,pid DESC")
            ->select();
        $show_from = array();
        foreach ($from as $key => $val) {
            $show_from[$val['from_id']] = $val['pname'] . '-' . $val['from_name'];
        }
        return $show_from;
    }
}